#include "apiordercache.h"
#include <sstream>
#include "minutelisten.h"
#include "util.h"
#include "log.h"


static bool __init__ = []()->bool {
    MinuteListen::Instance()->Register("ApiOrderMgr" , [&](std::int64_t tick){
        ApiOrderCache::Instance()->Reset();
    });
    return true;
}();

void ApiOrderCache::CacheMatchRegFailed(std::uint64_t order_id, Data&& data)
{
    m_matchreg_failed_group[order_id] = data;
}

ApiOrderCache::Data* ApiOrderCache::CheckMatchRegFailed(std::uint64_t order_id)
{
    auto it = m_matchreg_failed_group.find(order_id);
    if (m_matchreg_failed_group.end() == it)
    {
        return nullptr;
    }
    return &it->second;
}

void ApiOrderCache::ClearMatchRegFailed(std::uint64_t order_id)
{
    m_matchreg_failed_group.erase(order_id);
}

void ApiOrderCache::CacheCancelMatchReg(std::uint64_t order_id, std::uint64_t expire_time)
{
    m_cancle_matchreg_group[order_id] = expire_time;
}

bool ApiOrderCache::CheckCancelMatchReg(std::uint64_t order_id)
{
    return (m_cancle_matchreg_group.end() != m_cancle_matchreg_group.find(order_id));
}

void ApiOrderCache::ClearCancelMatchReg(std::uint64_t order_id)
{
    m_cancle_matchreg_group.erase(order_id);
}

void ApiOrderCache::Reset()
{
    // log_debug("reset");

    uint64_t now = CTools::GetUnixTime();
    for (auto it = m_matchreg_failed_group.begin(); it != m_matchreg_failed_group.end();)
    {
        if (now > it->second.expire_time)
        {
            it = m_matchreg_failed_group.erase(it);
        }
        else 
        {
            it++;
        }
    }
    for (auto it = m_cancle_matchreg_group.begin(); it != m_cancle_matchreg_group.end();)
    {
        if (now > it->second)
        {
            it = m_cancle_matchreg_group.erase(it);
        }
        else 
        {
            it++;
        }
    }
}













